﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.HomeServer.SDK.Interop.v1;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Search.Administration;
using Umbrella.Whs;

namespace Umbrella.Whs.SharePoint
{
    public sealed class WebsiteManager : SharePointConnected
    {
        public const string PropertyUmbrellaReleaseId = "UmbrellaReleaseId";

        private IWHSInfo2 _info;
        private string _domainName;
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(WebsiteManager));

        #region umbrella urls

        public Uri UmbrellaWebsiteUrl
        {
            get { return new Uri("http://" + Environment.MachineName + ":" + InstallationManager.UmbrellaWebsitePort); }
        }

        public Uri UmbrellaWebsiteUrlSecured
        {
            get { return new Uri("https://" + Environment.MachineName + ":" + InstallationManager.UmbrellaWebsitePort); }
        }

        public Uri UmbrellaDomainUrl
        {
            get
            {
                if (string.IsNullOrEmpty(_domainName))
                    return null;

                return new Uri("http://" + _domainName + ":" + InstallationManager.UmbrellaWebsitePort);
            }
        }

        public Uri UmbrellaDomainUrlSecured
        {
            get
            {
                if (string.IsNullOrEmpty(_domainName))
                    return null;

                return new Uri("https://" + _domainName + ":" + InstallationManager.UmbrellaWebsitePort);
            }
        }

        #endregion

        #region whs urls

        public Uri WhsWebsiteUrl
        {
            get { return new Uri("http://" + Environment.MachineName); }
        }

        public Uri WhsWebsiteUrlSecured
        {
            get { return new Uri("https://" + Environment.MachineName); }
        }

        public Uri WhsDomainUrl
        {
            get
            {
                if (string.IsNullOrEmpty(_domainName))
                    return null;

                return new Uri("http://" + _domainName);
            }
        }

        public Uri WhsDomainUrlSecured
        {
            get
            {
                if (string.IsNullOrEmpty(_domainName))
                    return null;

                return new Uri("https://" + _domainName);
            }
        }

        #endregion

        public string WhsDomainName
        {
            get { return _domainName; }
        }

        public string CreateEmailAddress(string user)
        {
            if (string.IsNullOrEmpty(user))
                throw new ArgumentException("null or empty", "user");

            // preapre
            var host = _domainName;

            if (string.IsNullOrEmpty(host))
                host = Environment.MachineName;

            // create
            return (user + "@" + host);
        }

        public SPWebApplication GetUmbrellaWebApplication()
        {
            return SPWebApplication.Lookup(this.UmbrellaWebsiteUrl);
        }

        public void RestartIIS()
        {
            for (; ; )
            {
                try
                {
                    var pi = new RunProcessLogged("iisreset", "/noforce", null);

                    pi.Run();

                    break;
                }
                catch (ProcessFailedException x)
                {
                    switch (x.ExitCode)
                    {
                        case 1061:  // Der Dienst kann zurzeit keine Steuerungsmeldungen annehmen. (2147943461, 80070425)
                            _log.Warn("Failed to perform iisreset; waiting 5 seconds...");

                            Thread.Sleep(5000);
                            break;

                        default:
                            // unknown exit code; rethrow!
                            throw;
                    }
                }
            }
        }

        /// <remarks>This function will trigger an IIS reset!</remarks>
        public void CreateUmbrellaWebsite(int languageLCID)
        {
            if (languageLCID < 0)
                throw new ArgumentException("value < 0", "languageLCID");

            if (languageLCID <= 0)
                languageLCID = Thread.CurrentThread.CurrentUICulture.LCID;

            _log.Info("Extending WHS website for language " + languageLCID + "...");

            try
            {
                // create website
                var r = CreateNewWebApplication(this.UmbrellaWebsiteUrl);

                // marks as created by umbrella
                r.Properties[PropertyUmbrellaReleaseId] = UmbrellaVersion.VersionId;

                r.Update();

                // deploy umbrella solution
                var solFile = new FileInfo(Whs.Properties.Constants.UmbrellaSharePointSolution);

                _log.Info("Deploying solution: " + solFile.Name +" ...");

                try
                {
                    this.Farm.Solutions.Remove(solFile.Name);
                }
                catch
                {
                    // ignore
                }

                var sol = this.Farm.Solutions.Add(solFile.FullName);

                sol.DeployLocal(
                    true,
                    new Collection<SPWebApplication>() { r },
                    true
                    );

                // restart IIS
                _log.Info("Restarting IIS...");

                RestartIIS();

                // create site collection
                CreateSiteCollection(
                    r,
                    Whs.Properties.Constants.UmbrellaSharePointSiteCollectionName,
                    languageLCID, 
                    Properties.Resources.txtExtendedWhsWebsiteTitle,
                    Properties.Resources.txtExtendedWhsWebsiteDesc
                    );

                _log.Info("WHS website extended; Configuring website...");

                // enable all file types
                r.BlockedFileExtensions.Clear();

                // add alternative mapping
                r.AlternateUrls.Add(new SPAlternateUrl(this.UmbrellaWebsiteUrlSecured, SPUrlZone.Intranet));

                if (this.UmbrellaDomainUrl != null)
                {
                    r.AlternateUrls.Add(new SPAlternateUrl(this.UmbrellaDomainUrl, SPUrlZone.Internet));
                    r.AlternateUrls.Add(new SPAlternateUrl(this.UmbrellaDomainUrlSecured, SPUrlZone.Internet));
                }

                r.AlternateUrls.Update();

                // enable self service
                r.SelfServiceSiteCreationEnabled = true;

                // enable WHS forms authentication
                /*{
                    var mods = new WebConfigModifications.EnableWhsFormsAuth();

                    mods.AddModification(r.WebConfigModifications);
                }*/

                // enable debugging
                {
                    var mods = new WebConfigModifications.EnableDebugging();

                    mods.AddModification(r.WebConfigModifications);
                }

                // flush config
                r.Update();

                this.WebService.ApplyWebConfigModifications();

                _log.Info("WHS website extended");

            }
            catch (Exception x)
            {
                _log.Error("Failed to extend WHS website", x);

                throw;
            }
        }

        public void CreateSiteCollection(SPWebApplication webApp, string templateName, int languageLCID, string title, string description)
        {
            if (webApp == null)
                throw new ArgumentNullException("webApp");

            if (string.IsNullOrEmpty(templateName))
                throw new ArgumentException("null or empty", "templateName");

            if (languageLCID < 0)
                throw new ArgumentException("value < 0", "languageLCID");

            if (string.IsNullOrEmpty(title))
                throw new ArgumentException("null or empty", "title");

            _log.Info("Creating site collection on " + webApp.Name + " for language " + languageLCID + ": " + templateName + " ...");

            try
            {
                var sa = SharePointServiceAccount.Load();
                var admin = new AdministratorAccount();

                using (webApp.Sites.Add(
                    "/",
                    title,
                    description ?? string.Empty,
                    (uint)languageLCID,
                    templateName,
                    admin.UserName,
                    admin.FullName,
                    admin.EmailAddress,
                    sa.UserName,
                    sa.FullName,
                    sa.EmailAddress
                    ))
                {
                    // do nothing
                }

            }
            catch (Exception x)
            {
                _log.Error("Failed to create site collection on " + webApp.Name + ": " + templateName, x);

                throw;
            }
        }

        public SPWebApplication CreateNewWebApplication(Uri url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            _log.Info("Creating web application: " + url + " ...");

            try
            {
                var b = new SPWebApplicationBuilder(this.Farm);

                var sa = SharePointServiceAccount.Load();
                var dm = new DatabaseManager();

                b.Id = Guid.NewGuid();
                b.ServerComment = ("SharePoint " + url.Host + " " + url.Port);

                b.CreateNewDatabase = true;
                b.DatabaseServer = dm.SqlServerName;
                b.DatabaseName = ("WSS_Content_" + url.Host + "_" + url.Port);

                b.Port = url.Port;
                b.UseSecureSocketsLayer = (url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase));
                b.DefaultZoneUri = url;
                //b.HostHeader = url.Host;

                b.IdentityType = IdentityType.SpecificUser;
                b.ApplicationPoolId = b.ServerComment;
                b.ApplicationPoolUsername = sa.UserName;
                b.ApplicationPoolPassword = sa.Password;

                b.AllowAnonymousAccess = false;
                b.UseNTLMExclusively = true;

                b.SearchServiceInstance = (SPSearchServiceInstance)this.SearchService.Instances[string.Empty];

                var r = b.Create();

                if (_log.IsDebugEnabled)
                    _log.Debug("Web application created; Provisioning...");

                r.Provision();

                _log.Info("Created web application: " + url);

                return r;
            }
            catch (Exception x)
            {
                _log.Error("Failed to create web application: " + url, x);

                throw;
            }
        }

        public void DeploySolutionToUmbrellaWebsite(FileInfo wspFile)
        {
            if (wspFile == null)
                throw new ArgumentNullException("wspFile");

            if (!wspFile.Exists)
                throw new ArgumentException("file does not exist: " + wspFile.FullName, "wspFile");

            // ensure the solution has been removed
            _log.Info("Remove WSP from solution store: " + wspFile.Name + " ...");

            try
            {
                this.Farm.Solutions.Remove(wspFile.Name);
            }
            catch (Exception x)
            {
                _log.Warn("Failed to remove solution: " + wspFile.Name, x);
            }

            // add the solution to the store
            _log.Info("Adding WSP to solution store: " + wspFile.FullName + " ...");

            SPSolution sol;

            try
            {
                sol = this.Farm.Solutions.Add(wspFile.FullName);
            }
            catch (Exception x)
            {
                _log.Error("Failed to add solution to store: " + wspFile.FullName, x);

                throw;
            }

            // deploy the solution inside the umbrella website
            try
            {
                sol.DeployLocal(
                    true,
                    new Collection<SPWebApplication>() { GetUmbrellaWebApplication() },
                    true
                    );
            }
            catch (Exception x)
            {
                _log.Error("Failed to deploy solution to Umbrella website: " + wspFile.Name, x);

                throw;
            }
        }

        public WebsiteManager()
        {
            _info = new WHSInfoClass();

            _info.Init(Whs.Properties.Constants.ApplicationName);

            // determine domain name
            var dn = _info.GetDomainName();

            if (!string.IsNullOrEmpty(dn))
            {
                var dni = new Uri(dn);

                _domainName = dni.Host;
            }
        }

    }
}
